<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增其他报工单</div>
            <div v-else-if="route.query?.info">
              其他报工单详情 <el-tag>{{ form.code }}</el-tag>
            </div>
            <div v-else>编辑其他报工单</div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" :loading="btnLoading" @click="submitForm"
              >保 存</el-button
            >
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="120px"
            >
              <el-row :gutter="20">
                <!-- <el-col :span="8">
                                    <el-form-item label="日报单编码" prop="createBy">
                                        <el-input v-model="form.createBy" readonly placeholder="自动带出" />
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="填报日期" prop="reportDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.reportDate"
                      value-format="YYYY-MM-DD "
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                                    <el-form-item label="工艺名称" prop="technologyType">
                                        <el-select v-model="form.technologyType" style="width: 200px"
                                        @blur="changeTechnologyType()">
                                            <el-option
                                                v-for="item in standard_technology_type"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="制单人" prop="createBy">
                    <el-input
                      v-model="form.createBy"
                      readonly
                      placeholder="自动带出"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="制单日期" prop="dutyDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.createTime"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="书刊类型" prop="bookType">
                    <el-select
                      v-model="form.bookType"
                      @change="changeOtherReportList"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in sys_standard_book_type"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="人员明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">人员明细</span>
          </template>
          <el-button
            size="small"
            type="primary"
            style="margin-bottom: 10px"
            v-if="!route.query.info"
            @click="handleAddReportUserList"
          >
            选择人员
          </el-button>
          <div class="order-form">
            <el-form
              :model="data"
              ref="reportUserListForm"
              :disabled="flag"
              class="data-form"
            >
              <el-table
                :data="data.reportUserList"
                ref="reportUserListRef"
                border
                :header-cell-class-name="mustPeople"
                :summary-method="getSummaries"
                show-summary
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  label="员工名称"
                  min-width="100"
                  prop="name"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="员工工号"
                  min-width="160"
                  prop="no"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="计件工资(元)"
                  min-width="150"
                  prop="wagesPiece"
                  align="center"
                >
                  <!-- <template #default="scope">
                    <el-form-item
                      :prop="'reportUserList.' + scope.$index + '.wagesPiece'"
                      :rules="[
                        {
                          required: true,
                          message: '计件工资',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        @blur="changeWagesSum(scope.row, scope.$index)"
                        v-model="scope.row.wagesPiece"
                        type="number"
                        placeholder="请输入计件工资(元)"
                      >
                        <template #append>元</template>
                      </el-input>
                    </el-form-item>
                  </template> -->
                </el-table-column>
                <!-- <el-table-column
                                    label="补助工资(元)"
                                    min-width="160"
                                    prop="wagesSubsidy"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item
                                           
                                        >
                                            <el-input
                                                @blur="changeWagesSum(scope.row, scope.$index)"
                                                v-model="scope.row.wagesSubsidy"
                                                type="number"
                                                placeholder="请输入补助工资(元)"
                                            >
                                                <template #append>元</template>
                                            </el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->
                <!-- <el-table-column
                                    label="合计工资(元)"
                                    min-width="120"
                                    prop="wagesSum"
                                    align="center"
                                ></el-table-column> -->
                <el-table-column
                  prop="proportion"
                  label="岗位占比"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      type="number"
                      @input="limitInput('proportion', scope.row)"
                      :disabled="flag"
                      v-model="scope.row.proportion"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  v-if="!flag"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDeletePeople(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="报工明细" name="3">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">报工明细</span>
          </template>
          <div class="order-form">
            <el-button
              size="small"
              type="primary"
              style="margin-bottom: 5px"
              v-if="!route.query.info"
              @click="handleAddOtherReport"
            >
              新增
            </el-button>
            <el-form :model="data" ref="otherReportForm" class="data-form">
              <el-table
                :data="data.otherReportList"
                border
                :header-cell-class-name="must"
                :summary-method="getSummariesWorkList"
                show-summary
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <!-- <el-table-column
                                    label="员工名称"
                                    width="100"
                                    prop="userName"
                                    align="center"
                                    v-if="!route.query.info"
                                >
                                <template #default="scope">
                                        <el-form-item
                                            :prop="'otherReportList.' + scope.$index + '.userName'"
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '员工名称',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                        <el-input
                                            v-model="scope.row.userName"
                                            readonly
                                            @click="handleAddPeopleList(scope.row, scope.$index)"
                                            placeholder="请选择"
                                        />
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="核算类型"
                  width="130"
                  prop="makeUp"
                  align="center"
                  v-if="!route.query.info"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'otherReportList.' + scope.$index + '.accountType'"
                      :rules="[
                        {
                          required: true,
                          message: '核算类型',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        :disabled="scope.row.produceNo"
                        style="width: 100%"
                        @change="changeAccontType(scope.row, scope.$index)"
                        v-model="scope.row.accountType"
                        placeholder="请选择核算类型"
                      >
                        <el-option
                          v-for="item in mes_account_type"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="核算类型"
                  width="130"
                  prop="accountType"
                  align="center"
                  v-else
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_account_type"
                      :value="scope.row.accountType"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="生产单编号"
                  min-width="180"
                  prop="produceNo"
                  align="center"
                  v-if="!route.query.info"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'otherReportList.' + scope.$index + '.produceNo'"
                      :rules="[
                        {
                          required: true,
                          message: '生产单编号',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        v-model="scope.row.produceNo"
                        readonly
                        @click="
                          handleAddTextProduceList(scope.row, scope.$index)
                        "
                        placeholder="请选择"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  v-else
                  label="生产单编号"
                  width="140"
                  prop="produceNo"
                  align="center"
                />
                <el-table-column
                  label="产品名称"
                  width="280"
                  prop="productName"
                  align="center"
                >
                  <!-- <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        v-model="scope.row.productName"
                        readonly
                        placeholder="自动带出"
                      />
                    </el-form-item>
                  </template> -->
                </el-table-column>
                <!-- <el-table-column
                  label="科目"
                  width="120"
                  prop="subjectType"
                  align="center"
                  v-if="!route.query.info"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-select
                        clearable
                        style="width: 100%"
                        v-model="scope.row.subjectType"
                        placeholder="请选择科目"
                        :disabled="flag"
                      >
                        <el-option
                          v-for="item in ems_workshop_subject_type"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="科目"
                  min-width="120"
                  prop="subjectType"
                  align="center"
                  v-else
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_workshop_subject_type"
                      :value="scope.row.subjectType"
                    />
                  </template>
                </el-table-column> -->
                <el-table-column
                  label="品种"
                  width="100"
                  prop="breed"
                  align="center"
                >
                  <!-- <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        v-model="scope.row.breed"
                        placeholder="请输入品种"
                      ></el-input>
                    </el-form-item>
                  </template> -->
                </el-table-column>
                <el-table-column
                  label="订单数量"
                  min-width="100"
                  prop="orderCount"
                  v-if="!route.query.info"
                  align="center"
                >
                  <!-- <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        type="number"
                        v-model="scope.row.orderCount"
                        placeholder="请输入订单数量"
                      ></el-input>
                    </el-form-item>
                  </template> -->
                </el-table-column>
                <el-table-column
                  label="订单数量"
                  min-width="200"
                  prop="orderCount"
                  v-else
                  align="center"
                />
                <el-table-column
                  label="完成数量"
                  prop="finshNum"
                  width="100"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'otherReportList.' + scope.$index + '.finshNum'"
                      :rules="[
                        {
                          required: true,
                          message: '完成数量',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        @blur="changefinshNum(scope.row, scope.$index)"
                        :disabled="flag"
                        type="number"
                        v-model="scope.row.finshNum"
                        placeholder="请输入完成数量"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="打包数"
                  prop="packNum"
                  width="100"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      v-if="
                        scope.row.accountType == '10' ||
                        scope.row.accountType == '11'
                      "
                      @blur="changefinshNum(scope.row, scope.$index)"
                      :disabled="flag"
                      type="number"
                      v-model="scope.row.packNum"
                      placeholder="请输入打包数"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="工价"
                  width="100"
                  prop="wages"
                  align="center"
                >
                  <!-- <template #default="scope">
                    <el-form-item
                      :prop="'otherReportList.' + scope.$index + '.wages'"
                      :rules="[
                        {
                          required: true,
                          message: '工价',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        :disabled="flag"
                        type="number"
                        v-model="scope.row.wages"
                        placeholder="根据工艺名称带出单价"
                      ></el-input>
                    </el-form-item>
                  </template> -->
                </el-table-column>
                <el-table-column
                  label="计件令数"
                  align="center"
                  width="120"
                  prop="pieceLing"
                >
                  <!-- <template #default="scope">
                    <el-form-item
                      :prop="'otherReportList.' + scope.$index + '.pieceLing'"
                      :rules="[
                        {
                          required: true,
                          message: '计件令数',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        :disabled="flag"
                        type="number"
                        v-model="scope.row.pieceLing"
                      ></el-input>
                    </el-form-item>
                  </template> -->
                </el-table-column>
                <el-table-column
                  label="预计用纸令数"
                  width="130"
                  prop="totalReamAmount"
                  align="center"
                />
                <el-table-column
                  label="本次用纸令数"
                  width="130"
                  prop="totalReamAmountBen"
                  align="center"
                />
                <el-table-column
                  label="总价"
                  width="130"
                  prop="totalPrice"
                  align="center"
                >
                  <!-- <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        type="number"
                        v-model="scope.row.totalPrice"
                        placeholder="自动计算"
                        readonly
                      ></el-input>
                    </el-form-item>
                  </template> -->
                </el-table-column>
                <el-table-column
                  label="累计上报量"
                  width="130"
                  prop="totalNum"
                  align="center"
                />
                <el-table-column
                  label="最大上报量"
                  width="130"
                  prop="maxNum"
                  align="center"
                />
                <el-table-column
                  label="备注"
                  width="120"
                  prop="remark"
                  align="center"
                  v-if="!route.query.info"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        v-model="scope.row.remark"
                        type="textarea"
                        placeholder="请输入备注"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  v-if="!flag"
                  label="操作"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <!-- <el-tooltip content="修改" placement="top" v-if="scope.row.id">
                                    <el-button link type="primary" icon="Edit" 
                                    @click="handleUpdate(scope.row,scope.row.index)">
                                </el-button>
                                </el-tooltip> -->
                    <el-tooltip content="删除" placement="top">
                      <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click="handleDelete(scope.row, scope.row.index)"
                      >
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <SearchPeoples
      :visible="searchPeopleVisible"
      :peopleSelectList="peopleSelectList"
      @changeUpdate="changePeopleData"
      @cancel="
        () => {
          searchPeopleVisible = false;
        }
      "
    ></SearchPeoples>
    <textProduceList
      :visible="textProduceListOpen"
      @changeUpdate="changetextProduceListData"
      :produceSelectList="produceSelectList"
      :params="params"
      :otherReport="accountType"
      @cancel="
        () => {
          textProduceListOpen = false;
          otherReport = '';
        }
      "
    >
    </textProduceList>
  </div>
</template>

<script setup>
import { addReportList, getReportById } from "@/api/production/otherReport.js";
import { orupdateList } from "@/api/production/standard.js";

import SearchPeoples from "@/components/SearchPeoples";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { toNumber } from "@/utils/ruoyi";
import textProduceList from "./textProduceList.vue";
import { nextTick } from "vue";
import { ElMessage } from "element-plus";
const route = useRoute();
const router = useRouter();
const searchVisible = ref(false);
const searchPeopleVisible = ref(false);
const textProduceListOpen = ref(false);
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const userInfo = useUserStore();
const peopleSelectList = ref([]);
const produceSelectList = ref([]);
const activeNames = ["1", "2", "3", "4"];
const userRef = ref(null);
const flag = ref(false);
const reportUserListForm = ref(null);
const btnLoading = ref(false);
const totalWagesSum = ref(0);
const accountType = ref("");
const totalAmount = ref(0);
const totalAmountH = ref(0);
const loading = ref(false);
const params = ref({});
const otherReportForm = ref(null);
const orupdateInfoList = ref([]);
const switchFlag = ref();
const totalPriceAmount = ref(0);
const { mes_account_type } = proxy.useDict("mes_account_type");

const data = reactive({
  otherReportList: [], //其他报工
  reportUserList: [], // 人员
  reportWorkList: [],
  form: {
    type: "1",
    bookType: "1",
  },
  rules: {
    bookType: [
      { required: true, message: "书刊类型不能为空", trigger: "change" },
    ],
    reportDate: [
      { required: true, message: "报工日期不能为空", trigger: "blur" },
    ],
    reportDate: [
      { required: true, message: "报工日期不能为空", trigger: "blur" },
    ],
    technologyType: [
      { required: true, message: "工艺名称不能为空", trigger: "blur" },
    ],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    technologyType: undefined,
  },
});
const { queryParams } = toRefs(data);
nextTick(() => {
  form.value.createBy = userInfo.name;
});

const getOrupdateList = () => {
  orupdateList({ pageNum: 1, pageSize: 100 })
    .then((res) => {
      orupdateInfoList.value = res.rows.filter(
        (item) => item.technologyType > 6
      );
    })
    .catch((err) => {});
};
getOrupdateList();

const {
  standard_technology_type,
  sys_standard_book_type,
  ems_workshop_subject_type,
} = proxy.useDict(
  "standard_technology_type",
  "sys_standard_book_type",
  "ems_workshop_subject_type"
);
const { form, rules, reportUserList, reportWorkList, otherReportList } =
  toRefs(data);
onActivated(() => {
  if (route.query?.id) {
    getReportById({ id: route.query.id }).then((res) => {
      Object.assign(form.value, { ...res.data });
      otherReportList.value = res.data.reportDetailList;
      reportUserList.value = res.data.reportUserList
        ? res.data.reportUserList
        : [];
      if (route.query.info) {
        flag.value = true;
      }
    });
  }
});

// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return toNumber(prev + curr, 2);
        } else {
          return toNumber(prev, 2);
        }
      }, 0)}`;
      if (column.property == "wagesPiece") {
        totalWagesSum.value = Number(sums[index]);
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};
// 合计
const getSummariesWorkList = (param) => {
  const { columns, data } = param;
  const sums = [];
  const fieldsToSum = ["totalPrice"];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (fieldsToSum.includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = ` ${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return toNumber(prev + curr, 2);
          } else {
            return toNumber(prev, 2);
          }
        }, 0)}`;
        if (column.property == "totalPrice") {
          totalPriceAmount.value = toNumber(sums[index], 2);
        }
      } else {
        sums[index] = "";
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

const findOrupdatePrice = (bookType, type) => {
  console.log(orupdateInfoList.value);
  return (
    orupdateInfoList.value.filter(
      (item) => item.technologyType == type && item.bookType === bookType
    )[0]?.pieceStandard || 0
  );
};
const changeAccontType = (row, index) => {
  accountType.value = row.accountType;
  row.wages = findOrupdatePrice(form.value.bookType, row.accountType);
  // changefinshNum(row, index);
};

const changeOtherReportList = (row) => {
  otherReportList.value = [];
};
//修改工艺名称
const changeTechnologyType = () => {
  queryParams.value.technologyType = form.value.technologyType;
  orupdateList(queryParams.value)
    .then((res) => {
      otherReportList.value.forEach((item, index) => {
        // item.wages = res.rows[0].pieceStandard;
        //总价
        item.totalPrice = toNumber(
          (Number(item.finshNum) || 0) * item.wages,
          2
        );
      });
    })
    .catch((err) => {
      loading.value = false;
    });
};

//修改完成数量
const changefinshNum = (row, index) => {
  if (!row.orderCount) {
    row.finshNum = null;
    row.totalPrice = 0;
    return ElMessage({
      message: "请先选择订单",
      type: "warning",
    });
  }
  if (Number(row?.finshNum) > Number(row?.maxNum)) {
    row.finshNum = null;
    row.totalPrice = 0;
    return ElMessage({
      message: "完成数量不能大于最大上报量",
      type: "warning",
    });
  }
  if (row.accountType == 19 || row.accountType == 20) {
    // 如果核算类型是书本裁切和八开卷裁切，需要增加计件令数字段，总价=计件令数*工价
    // 计件令数

    // //总价=计件令数*工价
    // otherReportList.value[index].totalPrice = toNumber(
    //   Number(otherReportList.value[index].pieceLing || 0) *
    //     Number(otherReportList.value[index].wages || 0),
    //   4
    // );
    //  2024-6-27   核算类型如果是八开卷裁切和书本裁切，计件金额=预计用纸令数*工价
    row.totalPrice = toNumber(
      Number(row.totalReamAmount || 0) * Number(row.wages || 0),
      4
    );
    /*** 2024-7-1
     * 4、完成数量/订单数量=本次用纸令数/预计用纸令数，根据此公式，计算本次用纸令数 = 完成数量✖️预计用纸令数/订单数量
     * 5、如果累计完成数量+完成数量>=0.99*订单数量，需要改这个品种的状态，不能再选择到
     * 6、总价=本次用纸令数*工价
     *  */
    row.totalReamAmountBen = toNumber(
      (Number(row.finshNum || 0) * Number(row.totalReamAmount || 0)) /
        Number(row.orderCount || 0),
      4
    );
    row.totalPrice = toNumber(
      Number(row.totalReamAmountBen || 0) * Number(row.wages || 0),
      2
    );
  } else if (row.accountType == 10 || row.accountType == 11) {
    if (row.packInNum) {
      if (
        Number(row.packNum) >
        Math.ceil(Number(row.finshNum) / Number(row.packInNum) + 5)
      ) {
        row.packNum = undefined;
        row.totalPrice = 0;
        return ElMessage({
          message: "不能超过完成数量的最大打包数",
          type: "warning",
        });
      }
    }

    // 打普通包  打捆打包
    row.totalPrice = toNumber(
      Number(row.packNum || 0) * Number(row.wages || 0),
      2
    );
  } else {
    row.totalPrice = toNumber(
      Number(row.finshNum || 0) * Number(row.wages || 0),
      2
    );
  }
  row.pieceLing = toNumber(Number(row.finshNum || 0) / 1000, 4);
  handleTotalCount();
};

const handleAddOtherReport = async () => {
  userRef.value.validate((v) => {
    if (!v) {
      return ElMessage({
        message: `请先选择书刊类型`,
        type: "warning",
      });
    }
    queryParams.value.technologyType = form.value.technologyType;
    orupdateList(queryParams.value)
      .then((res) => {
        otherReportList.value.push({
          // wages: res.rows[0].pieceStandard,
        });
      })
      .catch((err) => {
        loading.value = false;
      });
  });
  // textProduceListOpen.value = true;
};

const must = (obj) => {
  let mustColumns = [1, 6];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};

//限制只能输入4位小数
function limitInput(key, row) {
  row[key] =
    ("" + row[key]) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, "")
      .replace(/^0+(\d)/, "$1")
      .replace(/^\./, "0.")
      .match(/^\d*(\.?\d{0,1})/g)[0] || "";
  handleTotalCount();
}

const mustPeople = (obj) => {
  let mustColumns = [3, 4];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
const handleTotalCount = () => {
  // 计算计件工资
  const totalLing = otherReportList.value.reduce((prev, item) => {
    prev += Number(item.totalPrice || 0);
    return prev;
  }, 0);
  const totalProportion = reportUserList.value.reduce((prev, item) => {
    prev += Number(item.proportion || 0);
    return prev;
  }, 0);
  reportUserList.value.forEach((item) => {
    if (item.proportion) {
      item.wagesPiece = toNumber(
        (Number(item.proportion) / totalProportion) * totalLing,
        2
      );
      // item.wagesSum = toNumber(item.wagesPiece + Number(item.wagesSubsidy || 0), 2)
    }
  });
};
const textProduceIndex = ref(undefined);
const peopleIndex = ref(undefined);

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.reportDate = `${year}-${month}-${day}`;
  console.log(form.value.reportDate);
  form.value.createTime = `${year}-${month}-${day}`;
};
getCurrentDateTime();

// 删除
const handleDelete = (row, index) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    otherReportList.value = otherReportList.value.filter((item) => item != row);
    // if (row.id) {
    //   otherReportList.value = otherReportList.value.filter(
    //     (item) => item.id !== row.id
    //   );
    //   proxy.$modal.msgSuccess("删除成功");
    // } else {
    //   otherReportList.value.splice(index, 1);
    // }
    handleTotalCount();
  });
};
// 删除
const handleDeletePeople = (row, index) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    if (row.id) {
      reportUserList.value = reportUserList.value.filter(
        (item) => item.id !== row.id
      );
      handleTotalCount();
      proxy.$modal.msgSuccess("删除成功");
    }
  });
};

// 选择生产单
const handleAddTextProduceList = (row, index) => {
  if (!row.accountType) {
    return ElMessage({
      message: `请先选择核算类型`,
      type: "warning",
    });
  }
  textProduceIndex.value = index;
  textProduceListOpen.value = true;
};

// 选择人员
const handleAddReportUserList = () => {
  peopleSelectList.value = reportUserList.value;
  searchPeopleVisible.value = true;
};
// 选中的数据
const changetextProduceListData = (row) => {
  // const codeSet = new Set(otherReportList.value.map((data) => data.productId));
  // row.forEach((item) => {
  //   if (!codeSet.has(item.productId)) {
  //     otherReportList.value.push({ ...item });
  //     codeSet.add(item.productId);
  //   }
  // });
  const isRepeated = otherReportList.value.some((item) => {
    return (
      item.productId == row.productId && row.otherReport == item.accountType
    );
  });
  if (isRepeated) {
    return ElMessage({
      message: `存在相同核算类型的产品品种`,
      type: "warning",
    });
  }
  otherReportList.value[textProduceIndex.value].packInNum = row.packInNum;
  otherReportList.value[textProduceIndex.value].produceNo = row.produceNo;
  otherReportList.value[textProduceIndex.value].packNum = row.packInNum
    ? Math.ceil(Number(row.orderCount) / Number(row.packInNum))
    : 0;
  otherReportList.value[textProduceIndex.value].productName = row.productName;
  otherReportList.value[textProduceIndex.value].produceId = row.produceId;
  otherReportList.value[textProduceIndex.value].productId = row.productId;
  otherReportList.value[textProduceIndex.value].orderCount = row.orderCount;
  otherReportList.value[textProduceIndex.value].breed = row.breed;
  otherReportList.value[textProduceIndex.value].totalNum = row.totalNum;
  otherReportList.value[textProduceIndex.value].maxNum = row.maxNum;
  otherReportList.value[textProduceIndex.value].finshNum = row.maxNum;
  otherReportList.value[textProduceIndex.value].totalReamAmount =
    row.totalReamAmount;
  changefinshNum(otherReportList.value[textProduceIndex.value]);

  textProduceListOpen.value = false;
};

const handleAddPeopleList = (row, index) => {
  peopleSelectList.value = reportUserList.value;
  peopleIndex.value = index;
  searchPeopleVisible.value = true;
};

// 选中的人员
const changePeopleData = (row) => {
  const codeSet = new Set(reportUserList.value.map((data) => data.id));
  row.forEach((item) => {
    if (!codeSet.has(item.id)) {
      reportUserList.value.push({
        ...item,
        remark: null,
        no: item.code,
        proportion: 1,
      });
      codeSet.add(item.id);
    }
  });
  //   reportUserList.value = reportUserList.value.filter((item) =>
  //     row.some((rowItem) => rowItem.id === item.id)
  //   );
  if (otherReportList.value.length > 0) {
    handleTotalCount();
  }
  searchPeopleVisible.value = false;
};

//  返回
const goBack = () => {
  // router.replace({ path: "/production/otherReport" });
  // setTimeout(() => {
  //   tagsViewStore.delView(route);
  // }, 0);
  tagsViewStore.delView(route);
  router.go(-1);
};

// 清除主键
const clearId = (list, key) => {
  if (list.length > 0) {
    list.forEach((item) => {
      delete item[key];
    });
  }
};
// 保存
const submitForm = async () => {
  btnLoading.value = true;
  try {
    //debugger
    await userRef.value.validate();
    await reportUserListForm.value.validate();
    await otherReportForm.value.validate();
    if (reportUserList.value.length == 0) {
      btnLoading.value = false;
      return ElMessage({
        message: `请填写人员明细`,
        type: "warning",
      });
    }

    if (otherReportList.value.length == 0) {
      btnLoading.value = false;
      return ElMessage({
        message: `请填写报工明细`,
        type: "warning",
      });
    }
    // if (Number(totalWagesSum.value) !== Number(totalPriceAmount.value)) {
    //   btnLoading.value = false;
    //   return ElMessage({
    //     message: "合计工资与计件金额不符",
    //     type: "warning",
    //   });
    // }
    clearId(reportUserList.value, "id");
    if (route.query?.id) {
      // clearId(otherReportList.value, 'id')
      await addReportList({
        ...form.value,
        reportUserList: reportUserList.value,
        otherReportList: otherReportList.value,
      });
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
      goBack();
    } else {
      // 新增
      form.value.status = 0; //0:未审核 1：已审核  2：审核未通过
      await addReportList({
        ...form.value,
        reportUserList: reportUserList.value,
        reportDetailList: otherReportList.value,
      });
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      goBack();
    }
  } catch (error) {
    btnLoading.value = false;
    if (Object.keys(error)?.join(",").includes(".")) {
      const errInfoList = Object.values(error);
      const err = [];
      errInfoList.forEach((item) => {
        err.push(item[0].message);
      });
      ElMessage({
        message: `请将${err.join("、")}信息补充完整`,
        type: "warning",
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.order-form :deep(.el-form-item) {
  margin-bottom: 0px;
}
:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}
</style>